#include "MySqlClient.hpp"
#include "Util.hpp"
#include <iostream>
#include <vector>
#include "Database.hpp"
#include "OnlineManager.hpp"
#include "Room.hpp"
#include "Session.hpp"
#include "Matcher.hpp"
#include "Server.hpp"

static const std::string host = "localhost";
static const std::string user = "online_Gomoku";
static const std::string passwd = "88482bwasdAAA@";
static const std::string database = "online_Gomoku";

// 将进程切换为守护进程
int Daemon(int nochdir, int noclose)
{
    // 忽略管道关闭和子进程退出
    signal(SIGCHLD, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);
 
    // 切换为孙子进程, 因为进程组组长无法调用setsid
    if (fork() > 0) exit(0);
 
    // 设置为独立的会话组
    if (setsid() == -1)
    {
        return -1;
    }
 
    // 切换为孙子进程(不是新会话的首进程), 确保无法打开新的控制终端
    if (fork() > 0) exit(0);
 
    // 将工作目录切换为根目录
    if (!nochdir)
    {
        chdir("/");
    }
 
    // 将标准输入、输出、错误重定向到/dev/null
    if (!noclose)
    {
        // int fd = ::open("/dev/null", O_RDWR);
        // 这里希望所有日志全部输出到日志文件
        int fd = ::open("./log/online_Gomoku.log", O_RDWR);
        if (fd == -1)
        {
            return -1;
        }
        else
        {
            dup2(fd, 0);
            dup2(fd, 1);
            dup2(fd, 2);
        }
    }
    return 0;
}

int main()
{
    USE_FILE_STRATEGY("./log/online_Gomoku.log");
    Daemon(1, 1);
    Server srv(host, user, passwd, database);
    srv.Start(8888);
    return 0;
}